const pool = require('../database/pool');
const orderModel = require('../models/Order');

// 获取用户购物车
const getCart = async (req, res) => {
  try {
    const userId = req.user.id;
    const [cartItems] = await pool.execute(
      `SELECT c.*, d.name, d.price, d.image, d.stock 
       FROM cart c 
       JOIN drugs d ON c.drug_id = d.id 
       WHERE c.user_id = ?`,
      [userId]
    );
    res.json(cartItems);
  } catch (error) {
    console.error('获取购物车错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 获取购物车商品数量
const getCartCount = async (req, res) => {
  try {
    const userId = req.user.id;
    const [result] = await pool.execute(
      'SELECT SUM(quantity) as count FROM cart WHERE user_id = ?',
      [userId]
    );
    res.json({ count: result[0].count || 0 });
  } catch (error) {
    console.error('获取购物车数量错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 添加商品到购物车
const addToCart = async (req, res) => {
  try {
    const userId = req.user.id;
    const { drugId, quantity } = req.body;

    // 检查商品是否已在购物车中
    const [existingItems] = await pool.execute(
      'SELECT * FROM cart WHERE user_id = ? AND drug_id = ?',
      [userId, drugId]
    );

    if (existingItems.length > 0) {
      // 更新数量
      await pool.execute(
        'UPDATE cart SET quantity = quantity + ? WHERE user_id = ? AND drug_id = ?',
        [quantity, userId, drugId]
      );
    } else {
      // 添加新商品
      await pool.execute(
        'INSERT INTO cart (user_id, drug_id, quantity) VALUES (?, ?, ?)',
        [userId, drugId, quantity]
      );
    }

    res.status(201).json({ message: '添加成功' });
  } catch (error) {
    console.error('添加购物车错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 更新购物车商品数量
const updateCartItem = async (req, res) => {
  try {
    const userId = req.user.id;
    const { drugId } = req.params;
    const { quantity } = req.body;

    await pool.execute(
      'UPDATE cart SET quantity = ? WHERE user_id = ? AND drug_id = ?',
      [quantity, userId, drugId]
    );

    res.json({ message: '更新成功' });
  } catch (error) {
    console.error('更新购物车错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 从购物车删除商品
const removeFromCart = async (req, res) => {
  try {
    const userId = req.user.id;
    const { drugId } = req.params;

    await pool.execute(
      'DELETE FROM cart WHERE user_id = ? AND drug_id = ?',
      [userId, drugId]
    );

    res.json({ message: '删除成功' });
  } catch (error) {
    console.error('删除购物车商品错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 清空购物车
const clearCart = async (req, res) => {
  try {
    const userId = req.user.id;
    await pool.execute('DELETE FROM cart WHERE user_id = ?', [userId]);
    res.json({ message: '购物车已清空' });
  } catch (error) {
    console.error('清空购物车错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 结算购物车
const checkout = async (req, res) => {
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    const userId = req.user.id;

    // 获取购物车中的所有商品
    const [cartItems] = await connection.execute(
      `SELECT c.*, d.name, d.price, d.stock 
       FROM cart c 
       JOIN drugs d ON c.drug_id = d.id 
       WHERE c.user_id = ?`,
      [userId]
    );

    if (cartItems.length === 0) {
      return res.status(400).json({ message: '购物车为空' });
    }

    // 检查库存并创建订单
    for (const item of cartItems) {
      if (item.stock < item.quantity) {
        await connection.rollback();
        return res.status(400).json({ 
          message: `商品 ${item.name} 库存不足，当前库存: ${item.stock}` 
        });
      }

      // 创建订单
      await orderModel.createOrder(userId, item.drug_id, item.quantity);
    }

    // 清空购物车
    await connection.execute('DELETE FROM cart WHERE user_id = ?', [userId]);

    await connection.commit();
    res.json({ message: '结算成功' });
  } catch (error) {
    await connection.rollback();
    console.error('结算错误:', error);
    res.status(500).json({ message: '服务器错误' });
  } finally {
    connection.release();
  }
};

module.exports = {
  getCart,
  getCartCount,
  addToCart,
  updateCartItem,
  removeFromCart,
  clearCart,
  checkout
}; 